/**
 *  公共方法
 */
!(function (global, $) {
    var common = {};

    /*服务器IP*/
    common.GLOABURL = "http://222.196.35.35:9080/GSMS/";

    /**
     *  实现构造函数的继承
     * @param child 继承类
     * @param parent 被继承类
     */
    common.extend = function (child, parent) {
        var F = function () {
        };
        F.prototype = parent.prototype;
        child.prototype = new F();
        child.prototype.constructor = child;
        child.uber = parent.prototype;
    };

    /**
     * ajax
     * @constructor
     */
    var Ajax = function () {

    };

    /**
     * 生成sign签名
     * @param data
     * @returns {*}
     * @private
     */
    function _signData(data) {
        var signedData = data;
        return signedData;
    }

    Ajax.prototype = {
        get: function (url, data) {
            if (!url) {
                throw new Error("url is empty")
            }
            data = _signData(data);
            return $.get(url, data || {});
        },
        post: function (url, data) {
            if (!url) {
                throw new Error("url is empty")
            }
            data = _signData(data);
            return $.post(url, data || {});
        }

    };
    common.Ajax = Ajax;

    var EventListener = function () {
        this._listeners = [];
    };

    EventListener.prototype = {
        addEvent: function (type, fn) {
            this._listeners[type] = this._listeners[type] || [];
            if (typeof fn !== 'function') {
                throw new TypeError('注册事件fn参数只能为函数');
            }
            this._listeners[type].push(fn);
            return this;
        },
        fireEvent: function (type) {
            var eventsList = this._listeners[type];
            if (eventsList instanceof Array) {
                for (var i = 0, len = eventsList.length; i < len; i++) {
                    if (typeof eventsList[i] === 'function') {
                        eventsList[i]({
                            EVENTNAME: type
                        })
                    }
                }
            } else {
                throw new Error('触发未注册事件');
            }
        }
    };
    common.EventListener = EventListener;
    global.common = common;

})(typeof window !== 'undefined' ? window : this, jQuery);


/**
 *  List页面的基类
 */
!(function (global, $, _) {
    /**
     *
     * @param data:{}
     *  basicUrl[string]：页面的基本URL，必填，如"basic.original"
     *  listWithPara[object]:List请求携带的参数，可选
     *  currentId[string]:当前行的id，只有在双击行或者点击新增|修改按钮时触发
     *  addPageUrl[string]:add页面对应的路径
     *  toolBarSelector[string]:功能按钮的选择器如'#toolbar'
     *  columns[array]:datagrid的columns属性
     *  searchParam[object]:查询参数
     *
     * @methods prototype:{}
     *  init():
     *          由子类实现，初始化datagrid的结构和数据，页面手动调用
     *  updateCurrentPageData(data[?]:服务器返回的数据):
     *          更新页面数据，子类实现，由类中的setter或方法调用，一般情况下页面不手动调用
     *  openAddPage(id[string]:操作行的id)：
     *          打开add页面，子类无需再实现，由本类中currentId的set方法调用
     *  searchWithParam(parameter[object]:查询参数):
     *          由功能按钮【查看所有数据（parameter={}）】或查询按钮调用，子类写具体实现
     *
     * @events: 拓展事件用于注册函数，暂时没用到
     *  addEvent(type,fn):
     *  fireEvent(type):
     *  removeEvent(type,fn):
     * @constructor
     */
    var CommonList = function () {
        this._listeners = [];
    };


    CommonList.prototype = {
        set basicUrl(value) {
            this.data.basicUrl = value;
        },
        get basicUrl() {
            return this.data.basicUrl;
        },
        set listWithPara(value) {
            this.data.listWithPara = value;
        },
        get listWithPara() {
            return this.data.listWithPara;
        },
        set currentId(value) {
            this.data.currentId = value;
            this.openAddPage(value);
        },
        get currentId() {
            return this.data.currentId;
        },
        set addPageUrl(value) {
            this.data.addPageUrl = value;
        },
        get addPageUrl() {
            return this.data.addPageUrl;
        },
        set toolBarSelector(value) {
            this.data.toolBarSelector = value;
        },
        get toolBarSelector() {
            return this.data.toolBarSelector;
        },
        set columns(value) {
            this.data.columns = value;
        },
        get columns() {
            return this.data.columns;
        },
        set searchParam(value) {
            this.data.searchParam = value;
            this.searchWithParam(value);
        },
        get searchParam() {
            return this.data.searchParam;
        },
        init: function (columns) {

        },
        /**
         * 更新页面数据
         * @param data
         */
        updateCurrentPageData: function (data) {

        },
        /**
         * 双击列表行触发的事件
         * @param id
         */
        openAddPage: function (id) {
            open(this.addPageUrl + '?ID=' + id);
        },
        /**
         * 点击编辑按钮调用的事件
         * @param id
         */
        editCurentRow: function (id) {
            this.currentId = id;
            if (!id) {
                throw new Error('请选中某一行操作！');
            }
            open(this.addPageUrl);
        },
        /**
         * 查询按钮调用的事件
         * @param parameter
         */
        searchWithParam: function (parameter) {
            /**
             *  parameter = parameter || {};
             *   $("#dg").datagrid({
             *      queryParams: parameter
             *  })
             *
             */
        },

        /**
         * 注册事件，扩展本类及其子类的生命周期
         * @param type
         * @param fn
         * @returns {CommonList}
         */
        addEvent: function (type, fn) {
            this._listeners[type] = this._listeners[type] || [];
            if (typeof fn !== 'function') {
                throw new TypeError('注册事件fn参数只能为函数');
            }
            this._listeners[type].push(fn);
            return this;
        },
        /**
         * 触发事件
         * @param type
         * @returns {CommonList}
         */
        fireEvent: function (type) {
            var eventsList = this._listeners[type];
            if (eventsList instanceof Array) {
                for (var i = 0, len = eventsList.length; i < len; i++) {
                    if (typeof eventsList[i] === 'function') {
                        eventsList[i]({
                            EVENTNAME: type
                        })
                    }
                }
            } else {
                throw new Error('触发未注册事件');
            }
            return this;
        },
        /**
         * 移除事件
         * @param type
         * @param fn
         * @returns {CommonList}
         */
        removeEvent: function (type, fn) {
            var arrayEvent = this._listeners[type];
            if (typeof type === "string" && arrayEvent instanceof Array) {
                if (typeof fn === "function") {
                    for (var i = 0, length = arrayEvent.length; i < length; i += 1) {
                        if (arrayEvent[i] === fn) {
                            this._listeners[type].splice(i, 1);
                            break;
                        }
                    }
                } else {
                    delete this._listeners[type];
                }
            }
            return this;
        }
    };
    global.CommonList = CommonList;
})(typeof window !== "undefined" ? window : this, jQuery, common);


/**
 *  Add页面的基类
 */
!(function (global, $, _) {
    var CommonAdd = function () {
    };

    /**
     * 取得当前页面的参数对象
     */
    function getCurrentPagePara(name) {
        var paraArr = global.location.search.substring(1).split('&');
        var paraStr = '';
        var result = {};
        for (var i = 0, len = paraArr.length; i < len; i++) {
            if (paraArr[i].indexOf('=') !== -1) {
                paraStr = paraArr[i].split('=');
                result[paraStr[0]] = paraStr[1] || null;
            }
        }
        if (!name) {
            return result;
        }
        return result[name] || undefined;
    }

    CommonAdd.prototype = {
        set basicUrl(value) {
            this.data.basicUrl = value;
        },
        get basicUrl() {
            return this.data.basicUrl;
        },
        set maxId(value) {
            this.data.maxId = value;
        },
        get maxId() {
            return this.data.maxId;
        },
        set minId(value) {
            this.data.minId = value;
        },
        get minId() {
            return this.data.minId;
        },
        set listPageUrl(value) {
            this.data.listPageUrl = value;
        },
        get listPageUrl() {
            return this.data.listPageUrl;
        },
        set currentIndex(value) {
            this.data.currentIndex = value;
        },
        get currentIndex() {
            return this.data.currentIndex;
        },
        set currentId(value) {
            this.currentIndex = -1;
            this.data.currentId = value;
        },
        get currentId() {
            return this.data.currentId;
        },
        get currentData() {
            return this.data.currentData;
        },
        set currentData(value) {
            this.data.currentData = value;
            this.detailData = this.data.currentData.rows;
            this.updatePage();
        },
        set receiptData(value) {
            this.data.receiptData = value;
        },
        get receiptData() {
            return this.data.receiptData;
        },
        set detailData(value) {
            this.data.detailData = value;
        },
        get detailData() {
            return this.data.detailData;
        },
        init: function () {
            if (!this.basicUrl) {
                throw new Error('basicUrl[string] 不能为空');
                return;
            }
            this.currentIndex = -1;
            var me = this;
            this.getMaxAndMinId().done(function () {
                var id = getCurrentPagePara('ID') === undefined ? me.minId : getCurrentPagePara('ID');
                me.getRemoteDataById(_.GLOABURL + me.basicUrl + '/findbyid.do',id);
            });
        },
        getMaxAndMinId: function () {
            var ajax = new _.Ajax();
            var me = this;
            return ajax.get(_.GLOABURL + this.basicUrl + '/getmaxminid.do')
                .done(function (data) {
                    me.data.maxId = data.MAXID;
                    me.data.minId = data.MINID;
                }).fail(function (err) {
                    $.messager.alert('请求错误', '服务器请求异常', 'error');
                });
        },
        getRemoteDataById: function (url,id) {
            if (id == -1) {
                return;
            }
            if(!url || !id){
                $.messager.alert('参数错误', '空的URL[string]或ID[string]', 'error');
                return;
            }
            var ajax = new _.Ajax();
            var me = this;
            ajax.get(url, {ID: id}).done(function (data) {
                me.currentId = data.ID;
                me.currentData = me.deepCopy(data);
            }).fail(function (err) {
                $.messager.alert('请求错误', '服务器请求异常', 'error');
            });
        },
        updatePage: function (data) {
        },
        nextPage: function () {
            if(this.currentId >= this.maxId){
                $.messager.alert(" 提示", "没有下张");
                return;
            }
            this.getRemoteDataById(_.GLOABURL + this.basicUrl + '/next.do',this.currentId);
        },
        frontPage:function () {
            if(this.currentId <= this.minId){
                $.messager.alert(" 提示", "没有上张");
                return;
            }
            this.getRemoteDataById(_.GLOABURL + this.basicUrl + '/pre.do',this.currentId);
        },
        savePage:function(){
            var url = 'save.do';
            if(this.currentId == -1){
                url = 'update.do';
            }

        },
        deepCopy: function (o) {
            var isArray = o instanceof Array;
            var isObject = o instanceof Object;
            if (!isObject) return o;
            var n = (isArray ? [] : {});
            for (var k in o) n[k] = this.deepCopy(o[k]);
            return n;
        }
    };
    global.CommonAdd = CommonAdd;
})(typeof window !== "undefined" ? window : this, jQuery, common);